package cn.acewill.yxd.yunxundian.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;

import cn.acewill.yxd.yunxundian.Api.UpdateApi;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.CircleImageView;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.departBean;
import cn.acewill.yxd.yunxundian.pubClass.OKHttpUICallback;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.vdieogo.ActivityUtils;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.UpdateUtils;
import okhttp3.Call;


/**
 * Created by XXX on 2017/4/2.
 */
public class MyInfoFragment extends Fragment implements View.OnClickListener {

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private CircleImageView userPhoto;
    private TextView userName,userPosition;
    private int userId;
    private String lcVersion,descStr;
    //    public static String AppKey="0b60455cdea347bb89353c81555457e1";
//    public static String AccessToken="at.clzkd0n15oduzlzb68bhf0dr1gu8yd0m-1osh51vyz1-1rzr6jf-bcvp01074";
//    public static String Url="ezopen://AES:BSG3BwDh77Sl17lZKVB-Nw@open.ys7.com/768740072/1.hd.live";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.user_info,container,false);
        initView(view);
        try {
            loadUser();
        } catch (DbException e) {
            e.printStackTrace();
        }
        return view;
    }

    public void initView(View view){
        this.userId= MainActivity.id;
        RelativeLayout lyEffic = (RelativeLayout) view.findViewById(R.id.lyEffic);
        lyEffic.setOnClickListener(this);
        RelativeLayout lyPerson = (RelativeLayout) view.findViewById(R.id.lyPerson);
        lyPerson.setOnClickListener(this);
        RelativeLayout lyEmail = (RelativeLayout) view.findViewById(R.id.lyEmail);
        lyEmail.setOnClickListener(this);
        RelativeLayout rlout = (RelativeLayout) view.findViewById(R.id.rlOut);
        rlout.setOnClickListener(this);
//        this.scanCode= (TextView) view.findViewById(R.id.scanCode);
//        scanCode.setOnClickListener(this);
        TextView videoLive = (TextView) view.findViewById(R.id.videoLive);
        RelativeLayout lyVideo = (RelativeLayout) view.findViewById(R.id.lyVideo);
        videoLive.setOnClickListener(this);
        //显示直播
        if(pubClass.isEZplayVisible==1){
            lyVideo.setVisibility(View.GONE);
        }else{
            lyVideo.setVisibility(View.VISIBLE);
        }
        TextView localVersion = (TextView) view.findViewById(R.id.localVersion);
        RelativeLayout lyToolbox = (RelativeLayout) view.findViewById(R.id.lyToolbox);
        lyToolbox.setOnClickListener(this);
        RelativeLayout lyUpdate = (RelativeLayout) view.findViewById(R.id.lyUpdate);
        lyUpdate.setOnClickListener(this);
        this.userName= (TextView) view.findViewById(R.id.userName);
        this.userPhoto= (CircleImageView)view.findViewById(R.id.userPhoto);
        userPhoto.setOnClickListener(this);
        this.userPosition= (TextView) view.findViewById(R.id.userPosition);
        //设置版本号
        lcVersion = UpdateUtils.getVersion(getContext());
        localVersion.setText("当前版本："+lcVersion);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lyPerson:
                startActivityForResult(new Intent(getContext(),PersonActivity.class),1);
                break;
            case R.id.lyEffic:
               // startActivity(new Intent(getContext(),PersonEfficForOMActivity.class));

                startActivity(new Intent(getContext(),EfficManagerH5.class));
                break;
            case R.id.lyEmail:
                startActivity(new Intent(getContext(), EmailInfoActivity.class));
                break;
            case R.id.lyToolbox:
                startActivity(new Intent(getContext(), ToolBoxInfoActivity.class));
                break;
            case R.id.userPhoto:
                startActivity(new Intent(getContext(),PersonActivity.class));
                break;
            case R.id.videoLive:
                //用于账号登录
                ActivityUtils.goToLoginAgain(getContext());
                break;
            case R.id.lyUpdate:
                //获取服务器版本
                checkVersion();
                break;
            case R.id.rlOut:
            {
                new AlertDialog.Builder(this.getContext()).setTitle("确认退出吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“确认”后的操作
                                //MainActivity.this.finish();
                                System.exit(0);
                            }
                        })
                        .setNegativeButton("返回", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 点击“返回”后的操作,这里不设置没有任何操作
                            }
                        }).show();
            }

                break;
        }
    }

    public void loadUser() throws DbException {
        Employee emps = db.selector(Employee.class).where("ID", "=", userId).findFirst();
        userName.setText(emps.getUserName());
        int departId= emps.getDepartmentId();
        departBean departbean=db.selector(departBean.class).where("ID","=",departId+"").findFirst();
        if(departbean!=null)
        {
            userPosition.setText(departbean.getDepartmentName());
        }
        if (TextUtils.isEmpty(emps.getEmpImage())){
            userPhoto.setImageResource(R.mipmap.icon_logo);
        }else{
            String path=pubClass.pictureSavePath+ emps.getEmpImage();
            //加入站位图存在缓存的问题
            Glide.with(getContext()).load(path).error(R.mipmap.icon_error).into(userPhoto);
        }
    }

    //版本检查
    private void checkVersion(){
        readVersionData(pubClass.apkVersionInfoUrl);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 1:
                if(data!=null){
                    String path=data.getStringExtra("filePath");
                    Glide.with(getContext()).load(path).into(userPhoto);
                }
                break;
            case 2:
                try {
                    loadUser();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void weatherUpdate(final String url, String descStr, final int size){
        MaterialDialogUtils.showTitleMaterialDialog(getContext(), "版本更新", descStr, "确定", "取消", true, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                //开启下载
                if (NetWorkStateReceiver.netWorkType!=1){
                    MaterialDialogUtils.showMaterialDialog(getContext(), "当前使用是移动网络，将消耗"+UpdateUtils.caluateSize(size)+"流量，是否继续下载", "确定", "取消", true, false, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            UpdateApi.getInstance().downLoadApk(getContext(),url,pubClass.saveApkUrl);
                        }
                    }, new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    });
                }else{
                   UpdateApi.getInstance().downLoadApk(getContext(),url,pubClass.saveApkUrl);
                }

            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            }
        });
    }

    public void readVersionData(String url){
        try {
            OkHttpManger.getInstance().getAsync(url, new OKHttpUICallback.ResultCallback() {
                @Override
                public void onSuccess(String result) {
                    Log.e("versionResult",result);
                    if (result.contains("|")){
                        String[] res = result.split("\\|");
                        String version = res[0];
                        String url = res[1];
                        int size;
                        if (res[2].contains("kb")){
                            String str = res[2].replace("kb","");
                            size = Integer.parseInt(str);
                        }else{ 
                             size = Integer.parseInt(res[2]);
                        }
                        if (lcVersion.compareTo(version)<0){
                            //提示更新
                            weatherUpdate(url,res[3],size);
                        }else{
                            Toast.makeText(getContext(),"已是最新版本",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                @Override
                public void onError(Call call, IOException e) {
                    Toast.makeText(getContext(),"服务器返回错误",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
